package edu.wit.acl.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.wit.acl.entity.Role;
import edu.wit.acl.entity.RoleCapacity;
import edu.wit.acl.entity.RoleProject;
import edu.wit.acl.entity.User;
import edu.wit.common.annotation.Log;
import edu.wit.common.enums.BusinessType;
import edu.wit.common.result.R;
import edu.wit.common.security.service.TokenService;
import edu.wit.common.utils.UUIDGenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2020-01-12
 */
@RestController
@RequestMapping("/admin/acl/role")
//@CrossOrigin
@Api(tags = "角色模块")
public class RoleController extends BaseController {

    @Autowired
    private TokenService tokenService;

    @ApiOperation(value = "获取角色分页列表")
    @GetMapping("{page}/{limit}/{category}")
    @Log(title = "获取角色分页列表", businessType = BusinessType.SELECT)
    public R index(
            @ApiParam(name = "page", value = "当前页码", required = true)
            @PathVariable Long page,
            @ApiParam(name = "limit", value = "每页记录数", required = true)
            @PathVariable Long limit,
            @ApiParam(name = "category", value = "角色类别", required = true)
            @PathVariable Long category,
            Role role) {
        Page<Role> pageParam = new Page<>(page, limit);
        QueryWrapper<Role> wrapper = new QueryWrapper<>();

        if (!StringUtils.isEmpty(role.getRoleName())) {
            wrapper.like("role_name", role.getRoleName());
        }

        wrapper.eq("category", category);
        if (category == 3) {
            User user = userService.selectByUsername(tokenService.getLoginUserByToken().getUsername());
            if (!user.getPid().equals("0")) {
            /*
               说明不是租户超管，则该用户属于租户超管下的~
             */
                wrapper.eq("parent_admin_id", user.getPid());
            } else {
                wrapper.eq("parent_admin_id", user.getId());
            }
        }
        roleService.page(pageParam, wrapper);
        List<Role> roleList = pageParam.getRecords();


        roleList.forEach(role1 -> {
            role1.setRolesNum(userRoleService.selectRoleNums(role1.getId()));
            User user = userService.selectById(role1.getOperatorId());
            role1.setOperator(user.getNickName());
            String companyName = roleService.selectCompanyNameByCompanyId(role1.getCompanyId());
            if (companyName == null) {
                role1.setCompanyName("项目方");
            } else {
                role1.setCompanyName(companyName);
            }
        });

        return R.ok().data("items", roleList).data("total", pageParam.getTotal());
    }

    @ApiOperation(value = "获取角色")
    @GetMapping("get/{id}")
    @Log(title = "获取角色", businessType = BusinessType.SELECT)
    public R get(@PathVariable String id) {
        Role role = roleService.getById(id);
        return R.ok().data("item", role);
    }

    @ApiOperation(value = "新增角色")
    @PostMapping("save")
    @Log(title = "新增角色", businessType = BusinessType.INSERT)
    public R save(@RequestBody Role role) {
        User user = userService.selectByUsername(tokenService.getLoginUserByToken().getUsername());
        role.setOperatorId(user.getId());
        if (role.getCategory() == 3) {
            role.setParentAdminId(user.getPid().equals("0") ? user.getId() : user.getPid());
        }
        Long generate = UUIDGenUtil.generate();

        role.setId(generate + "");

        roleService.save(role);

//        roleService.selectByRoleNameAndCompanyId(role.getRoleName(),role.getCompanyId());

        return R.ok().data("roleId",generate+"");
    }

    @ApiOperation(value = "修改角色")
    @PutMapping("update")
    @Log(title = "修改角色", businessType = BusinessType.UPDATE)
    public R updateById(@RequestBody Role role) {
        roleService.updateById(role);
        return R.ok();
    }

    @ApiOperation(value = "删除角色")
    @DeleteMapping("remove/{id}")
    @Log(title = "删除角色", businessType = BusinessType.DELETE)
    public R remove(@PathVariable String id) {
        roleService.removeById(id);
        return R.ok();
    }

    @ApiOperation(value = "根据id列表删除角色")
    @DeleteMapping("batchRemove")
    @Log(title = "根据id列表删除角色", businessType = BusinessType.DELETE)
    public R batchRemove(@RequestBody List<String> idList) {
        roleService.removeByIds(idList);
        return R.ok();
    }

    @GetMapping("/changeStatus/{id}")
    public R changeStatus(@PathVariable String id) {

        Role role = roleService.selectByRoleId(id);
        if (role.getStatus().equals("0")) {
            role.setStatus("1");
        } else {
            role.setStatus("0");
        }

        System.out.println("更新后role=" + role);
        boolean b = roleService.updateById(role);

        if (b) {
            return R.ok();
        } else {
            return R.error().code(201).message("修改失败");
        }
    }

    @PostMapping("/distributeEventToRole/{roleId}")
    @ApiOperation(value = "给角色分配项目，应该传入角色id，和项目ids")
    public R distributeEventToRole(@RequestBody Long[] projectIds, @PathVariable Long roleId) {
         /*
            先删除原有的，然后再重新添加，避免重复添加相同的关联属性
         */
        roleProjectService.remove(new QueryWrapper<RoleProject>().eq("role_id", roleId));
        for (Long projectId : projectIds) {
            RoleProject roleProject = new RoleProject();
            roleProject.setRoleId(roleId.toString());
            roleProject.setProjectId(projectId.toString());
            roleProjectService.save(roleProject);
        }
        return R.ok();
    }

    @GetMapping("/getRolesByCompanyId")
    @ApiOperation("根据劳务公司id查询角色")
    public R getRolesByCompanyId(@RequestParam("companyId") String companyId) {
        List<Role> roles = roleService.selectByCompanyId(companyId);
        return R.ok().data("roles",roles);
    }

    /**
     *   -----------------------------------------------------------角色分配容量方法
     */
    @PostMapping("/saveRoleCapacity")
    @ApiOperation("根据角色分配用户容量")
    public R saveRoleCapacity(@RequestBody RoleCapacity roleCapacity) {

//        if (roleCapacity.getRoleId() != null) {
//            roleCapacityService.updateRoleCapacity(roleCapacity);
//        } else {
//            roleCapacityService.saveRoleCapacity(roleCapacity);
//        }

        roleCapacityService.saveRoleCapacity(roleCapacity);

        return R.ok();
    }

    @PostMapping("/updateRoleCapacity")
    @ApiOperation("根据角色修改用户容量")
    public R updateRoleCapacity(@RequestBody RoleCapacity roleCapacity) {
        roleCapacityService.updateById(roleCapacity);
        return R.ok();
    }

    @GetMapping("/removeRoleCapacity/{roleId}")
    @ApiOperation("根据角色id删除用户容量")
    public R removeRoleCapacity(@PathVariable String roleId) {
        roleCapacityService.removeRoleCapacity(roleId);
        return R.ok();
    }

    @GetMapping("/selectRoleCapacity/{roleId}")
    @ApiOperation("根据角色查看用户容量")
    public R selectRoleCapacity(@PathVariable String roleId) {
        return R.ok().data("roleCapacity",roleCapacityService.selectRoleCapacity(roleId));
    }
}

